package xiaobange.filter;

import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;
import xiaobange.common.BaseConText;
import xiaobange.common.R;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@WebFilter(filterName = "EmployeeWebFilter",urlPatterns = "/*")
@Slf4j
public class EmployeeWebFilter implements Filter {
    //住啊们用来做路径比较的
    private static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前请求路径
        String requestURI = request.getRequestURI();
        //设置白名单通行
        String[] URIS = new String[]{
                "/employee/login",//登录请求
                "/employee/logout",//退出登录请求
                "/backend/**",//静态资源请求
                "/front/**",//手机端静态资源请求
                "/common/**",
                "/favicon.ico",
                "/user/loginout",
                "/user/login",
                "/user/sendMsg",
                "user/login"
        };
        //白名单放行
        if (CheckURI(URIS,requestURI)){
            filterChain.doFilter(request,response);
            return;
        }
        //判断用户是否登录
        if (request.getSession().getAttribute("employee") != null){
            //将Session存入当前线程工具类中
            BaseConText.setThreadSessionID((Long) request.getSession().getAttribute("employee"));
            filterChain.doFilter(request,response);
            return;
        }
        //判断手机端用户是否登录
        if (request.getSession().getAttribute("user") != null){
            //将Session存入当前线程工具类中
            BaseConText.setThreadSessionID((Long) request.getSession().getAttribute("user"));
            filterChain.doFilter(request,response);
            return;
        }
        log.info("用户未登录，拦截地址：{}",requestURI);
        //如果都不成立那么返回响应的结果给前端页面
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否放行
     * @param Uris
     * @param ThisUri
     * @return
     */
    private static boolean CheckURI(String[] Uris,String ThisUri){
        for (String s : Uris) {
            boolean match = PATH_MATCHER.match(s, ThisUri);
            if (match){
                return true;
            }
        }
        return false;
    }
}
